package com.fingard.dsp.bank.helpers.dbhelpers;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.text.XmlHelper;
import com.fingard.xml.XElement;

public class SerializeHelper {

	/**将对象转成xml，每个字段一个属性，如 <item a="b" />
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException
	 * @param pObj要转为xml报文的对象
	 * @param pIgnoreFields忽略的字段（不转xml的），需要小写*/
	public static String toXmlItemByAttr(Object pObj, HashSet<String> pIgnoreFields) throws IllegalArgumentException, IllegalAccessException{
		StringBuilder sbXml = new StringBuilder();
		Field[] fields = pObj.getClass().getFields();
		sbXml.append("<item");
		for(int i=0;i<fields.length;i++){
			String eachType = fields[i].getGenericType().toString().toLowerCase();
			String aName = fields[i].getName();
			if(pIgnoreFields !=null && pIgnoreFields.contains(aName.toLowerCase())){
				continue;
			}
			sbXml.append(" " + aName + "=\"");
			Object val = fields[i].get(pObj);
			if(eachType.contains("date")){
				if(val != null && val.toString().length() > 0){
					sbXml.append(new SimpleDateFormat(Format.DateIsoFormatStr).format(val));
				}
			}else if(val != null){
				sbXml.append(XmlHelper.encodeFull(val.toString()));
			}
			sbXml.append("\"");
		}
		sbXml.append(" />");
		return sbXml.toString();
	}
	
	/**通过xml节点的属性装载对象，如<item a="v1" b="v2" />
	 * @throws Exception */
	public static void loadObjectFromXeAttr(XElement pXe, Object pClass) throws Exception {
		if(pXe.hashMapAttributes != null){
			HashMap<String, Object> map = new HashMap<String, Object>();
			for(Map.Entry<String, String> eachEntry : pXe.hashMapAttributes.entrySet()){
				map.put(eachEntry.getKey().toUpperCase(), eachEntry.getValue());
			}
			LoadHelper.loadObject(map, pClass);
		}else{
			throw new Exception("pXe对象为空，不能执行loadObjectFromXeAttr");
		}
	}
}
